package com.jieao.template.common.aop;


import cn.hutool.json.JSON;
import com.jieao.template.common.util.CommonUtils;
import com.jieao.template.common.util.JsonUtils;
import com.jieao.template.entity.pub.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局日志
 *
 * @author Jzw
 * @className LogRecordAspect
 * @since 2020-07-15 09:19
 */
@Aspect
@Component
@Slf4j
public class LogRecordAspect
{
    @Pointcut("execution(* com.jieao.template.controller..*.*(..))")
    public void excludeService()
    {
    }


    @Around("excludeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable
    {
        String requestId = CommonUtils.generateShortUUID();
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        assert sra != null;
        HttpServletRequest request = sra.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String queryString = request.getQueryString();
        Object[] args = pjp.getArgs();
        String params = "";
        if (args.length > 0)
        {
            if ("GET".equals(method) || "DELETE".equals(method))
            {
                params = queryString;
            }
            else
            {
                params = JsonUtils.objectToJson(args);
            }
        }
        log.info("类名 : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
        log.info("请求 : " + requestId + ",开始===地址:" + url);
        log.info("请求 : " + requestId + "开始===类型:" + method);
        log.info("请求 : " + requestId + "开始===参数:" + params);

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        if (result instanceof JsonData)
        {
            log.info("请求 : " + requestId + "结束===返回值:" + JsonUtils.objectToJson(result));
        }
        else
        {
            log.info("请求 : " + requestId + "结束===返回值:返回格式非JsonData");
        }
        return result;
    }

}
